package com.bike.bikeserver.controller.backend;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSONObject;
import com.bike.bikeserver.common.utils.HttpUtils;
import com.bike.bikeserver.common.utils.ImageUtils;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.bike.bikeserver.constant.ModelParamConstant.DEEPLAB_NO_OV_URL;
import static com.bike.bikeserver.constant.ModelParamConstant.YOLO_NO_OV_URL;

/**
 * @version 1.0
 * @Author ZZX
 * @Date 2023/7/4 16:29
 */
@Slf4j
@RestController
@RequestMapping("/testProject")
public class TestController2
{
    @SaIgnore
    @GetMapping("getInfo")
    public String testInfo()
    {
        log.info("测试日志功能");
        // 获取当前时间的毫秒级时间戳
        long timestamp = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timestampString = sdf.format(new Date(timestamp));
        Long aLong = Long.valueOf(timestampString);
        System.out.println(aLong);
        // 生成随机数
        Random random = new Random();
        int randomNumber = random.nextInt(100); // 生成范围在 0 到 99 的随机数

        // 打印结果
        System.out.println("Timestamp String: " + timestampString);
        System.out.println("Timestamp Long: " + timestamp);
        System.out.println("Random Number: " + randomNumber);
        return "ok";
    }

    @SaIgnore
    @PostMapping("fakeImageUpload")
    public void fakeImageUpload(MultipartFile file)
    {
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + "tempFile";
        // 目录是否存在，没有则新建
        if (!FileUtil.exist(globalCodePathName))
        {
            FileUtil.mkdir(globalCodePathName);
        }
        // 把用户的文件隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        File newFile = new File(userCodeParentPath);
        try
        {
            // 真上传
            file.transferTo(newFile);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            // 删除：假上传
            boolean delete = newFile.delete();
            log.info("[假]上传结果：{}", delete);
        }
    }

    @Autowired
    StringEncryptor encryptor;

    @GetMapping("getEncPwd")
    public void getEncPwd()
    {
        System.out.println("database:");
        String username = encryptor.encrypt("root");
        System.out.println(username);

        String password = encryptor.encrypt("underdog");
        System.out.println(password);

        // mail
        System.out.println("mail:");
        String username2 = encryptor.encrypt("1504163880@qq.com");
        System.out.println(username2);

        String password2 = encryptor.encrypt("lecwkqcfiklvbafd");
        System.out.println(password2);

        // druid
        System.out.println("druid:");
        String username3 = encryptor.encrypt("zzx");
        System.out.println(username3);

        String password3 = encryptor.encrypt("123456");
        System.out.println(password3);
    }

    @GetMapping("testYoloApi")
    public void testYoloApi()
    {
        String api = YOLO_NO_OV_URL;
        JSONObject params = new JSONObject();
        ArrayList<String> imageCodes = new ArrayList<>();
        imageCodes.add(ImageUtils.getImgFileToBase64("F:\\items\\bike-model\\data-v2（1303）\\images\\0001.jpg"));
        imageCodes.add(ImageUtils.getImgFileToBase64("F:\\items\\bike-model\\data-v2（1303）\\images\\0002.jpg"));
        params.put("imageCodes", imageCodes);
        log.info("请求地址为：" + api + "，请求参数名为：" + "imagesCodes");
        ResponseEntity<String> response = HttpUtils.sendPostV2(api, params);
        String responseBody = response.getBody();
        JSONObject jsonObject = JSONObject.parseObject(responseBody);
        String resLogs = jsonObject.getString("logs");
        log.info("请求地址为：" + api + "，返回日志结果为：" + resLogs);
    }

    @GetMapping("testDeeplabApi")
    public void testDeepLabApi()
    {
        String api = DEEPLAB_NO_OV_URL;
        JSONObject params = new JSONObject();
        ArrayList<String> imageCodes = new ArrayList<>();
        imageCodes.add("data:image/jpg" + ";base64," + ImageUtils.getImgFileToBase64("F:\\items\\bike-model\\bike-segmentation\\temp\\datav2\\0003.jpg"));
        imageCodes.add("data:image/jpg" + ";base64," + ImageUtils.getImgFileToBase64("F:\\items\\bike-model\\bike-segmentation\\temp\\datav2\\0004.jpg"));
        params.put("isResize", false);
        params.put("imageCodes", imageCodes);
        log.info("请求地址为：" + api + "，请求参数为：" + params);
        ResponseEntity<String> response = HttpUtils.sendPostV2(api, params);
        String responseBody = response.getBody();
        JSONObject jsonObject = JSONObject.parseObject(responseBody);
        String resLogs = jsonObject.getString("details");
        log.info("请求地址为：" + api + "，返回日志结果为：" + resLogs);
    }

    // 只处理单张，多了速度就慢了
    @GetMapping("getIfTooManyBikes")
    public void getIfTooManyBikes()
    {
        String api = YOLO_NO_OV_URL;
        JSONObject params = new JSONObject();
        ArrayList<String> imageCodes = new ArrayList<>();
        imageCodes.add("data:image/jpeg" + ";base64," + ImageUtils.getImgFileToBase64("F:\\items\\bike-model\\测试专用小图片\\0.jpeg"));
        params.put("imageCodes", imageCodes);
        log.info("请求地址为：" + api);
        ResponseEntity<String> response = HttpUtils.sendPostV2(api, params);
        String responseBody = response.getBody();
        JSONObject jsonObject = JSONObject.parseObject(responseBody);
        String resLogs = jsonObject.getString("logs");
        log.info("请求地址为：" + api + "，返回日志结果为：" + resLogs);
        String pattern = "\\d+\\s+shared_bike";
        Pattern regexPattern = Pattern.compile(pattern);
        Matcher matcher = regexPattern.matcher(resLogs);
        int count = 0;
        if (matcher.find())
        {
            String matchedText = matcher.group();
            String[] parts = matchedText.split(" ");
            if (parts.length > 1)
            {
                count = Integer.parseInt(parts[0]);
                System.out.println("Count of shared_bikes: " + count);
            }
        }
    }
}
